jQuery(document).ready( function($) {
    $('.wpfp-link').live('click', function(e) {
        dhis = $(this);
        wpfp_do_js( dhis, 1 );
        // for favorite post listing page
        if (dhis.hasClass('remove-parent')) {
            dhis.parent("li").fadeOut();
        }
        return false;
    });
});

function getCookie(name) {
  var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
  return r ? r[1] : undefined;
}

function wpfp_do_js( dhis, doAjax ) {
    loadingImg = dhis.prev();
    loadingImg.show();
    beforeImg = dhis.prev().prev();
    beforeImg.hide();
    //url = document.location.href.split('#')[0];
    url = dhis.attr('href').split('?')[0]
    params = dhis.attr('href').split('?')[1] + '&_xsrf=' + getCookie("_xsrf");
    params = params.split('&')

    var Arr = {}
    for(x in params){
        if (params[x] != ''){
            param = params[x].split("=")
            Arr[param[0]]= param[1]
        }
    }
    if ( doAjax ) {
        jQuery.post(url, Arr, function(data) {
                dataJson = eval(data)
                if(dataJson.code == 110 || dataJson.code ==120){
                    alert(dataJson.message)
                    location.href = "/user/login"
                }
                dhis.parent().html(dataJson.message);
                if(typeof wpfp_after_ajax == 'function') {
                    wpfp_after_ajax( dhis ); // use this like a wp action.
                }
                loadingImg.hide();
            }
        );
    }
}
